var express = require('express');
var router = express.Router();
var db = require("../db");
var moment = require("moment");

/* GET users listing. */
router.get('/editor/:id', function (req, res) {
  db.Student.findById(req.params.id, function (err, data) {
    if (data) {

    } else {
      data = new db.Student();
    }
    data.dateForShow = moment(data.birthday).format("YYYY-MM-DD");
    res.render("editor", {
      student: data
    })
  })
});

router.post('/editor/:id', function (req, res) {
  console.log(req.body.birthday);
  req.body.age = (new Date().getFullYear() - new Date(req.body.birthday).getFullYear());

  db.Student.findByIdAndUpdate(req.params.id, req.body, { upsert: true }, function (err) {
    if (!err) {
      res.redirect('/api/v1/list/1');
    }
  })
})

router.post("/delete", function (req, res) {
  db.Student.findByIdAndRemove(req.body.id, function (err) {
    if (!err) {
      res.redirect('/api/v1/list/1');
    }
  })
})

module.exports = router;
